<?php

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

if(empty($_G['uid'])){
	showmessage('to_login', '', array(), array('showmsg' => true, 'login' => 1));
}
require_once libfile('function/core');
require_once libfile('function/vote');
require_once libfile('function/database');

$uid = $_G['uid'];
$aid = intval(getgpc('aid'));
$agree = getgpc('agree');
if ('agree' != $agree) {
	$message = lang('bid/template', 'agree_must');
	showmessage($message, "bid.php?mod=entry&aid=$aid&uid=$uid", array(), array('showmsg' => true, 'alert' => 'error'));
}


$activity = get_activity($aid);
$credits_rule = $activity['credits_rule'];
if (empty($credits_rule)) {
	$credits_rule = get_default_credits_rule();
}

$catchword = getgpc('catchword');
$description = getgpc('description');
$bid_gold_coin = getgpc('bid_gold_coin');
if ( empty($bid_gold_coin) || $bid_gold_coin < 0 ) {
	$bid_gold_coin = 0;
}

$vote_user = array('aid' => $aid, 'uid' => $_G['uid'], 'user_name' => $_G['username'],  'catchword' => $catchword, 'description' => $description);
$vote_user['insert_time'] = $vote_user['update_time'] = time();

$user_gold_coin = get_gold_coin();
$activity_gold_coin = ($activity['entry_fee'] + $bid_gold_coin);

// 检查报名用户是否有足够的金币。是否可以报名。
if (check_entry_submit($user_gold_coin, $activity_gold_coin)) {
	$id = DB::insert('vote_user', $vote_user, true, false, true);
	if ($id){
		// 更新 vote_user_count
		$vote_user_count = array('id' => $id, 'aid' => $vote_user['aid'], 'uid' => $vote_user['uid'], 'bid_gold_coin' => $bid_gold_coin);
		DB::insert('vote_user_count', $vote_user_count, false, false, true);

		// 扣减金币。更新参赛人数
		updatemembercount($_G['uid'], array(get_gold_coin_field() => (0 - $activity_gold_coin)), true, 'ENT', $_G['uid']);
		$sql = ' select  count(*) as user_count from '.DB::table('vote_user').' a where aid = '.$aid;
		$tmp = DB::fetch_first($sql);
		$user_count  = $tmp['user_count'];

		DB::insert('vote_activity_count', array('id' => $activity['id'], 'user_count' => $user_count), false, true, true);
		require_once 'setimg.php';
	}
	else {
		$old_activity = fetch_first('vote_user', array('uid' => $vote_user['uid'], 'aid' => $vote_user['aid']));
		if(!empty($old_activity)){
			// TODO
			$message = lang('bid/template', 'duplicate_entry');
			showmessage($message, 'bid.php?mod=user', array(), array('showmsg' => true, 'alert' => 'error'));
		}
		else {
			// TODO ERROR
		}
	}

}
else {
	$bid_gold_coin = empty($vote_user['bid_gold_coin']) ? 0 : intval($vote_user['bid_gold_coin']);
	$message = lang('bid/template', 'not_enough_gold_coin',
	array('user_gold_coin' => get_gold_coin(), 'activity_gold_coin' => $activity_gold_coin, 'entry_fee' => $activity['entry_fee'],
				'bid_gold_coin' => $bid_gold_coin));

	showmessage($message, '', array(), array('showmsg' => true, 'alert' => 'info'));
}
?>